package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;

public class AccessTokenUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);
    
    private static final int HOUR_TIMEOUT = 2;
    
    public static String getAccessToken(Integer type) {
        String access_token ;
        //1:获取itn_access_token; 0获取openapi_access_token
        if(type == 1){
             access_token = SessionHelper.getInstance().fetchInfoByKey(CacheKeys.ITN_ACCESS_TOKEN);
        }else{
             access_token = SessionHelper.getInstance().fetchInfoByKey(CacheKeys.OPENAPI_ACCESS_TOKEN);
        }
        if (StringUtils.isBlank(access_token)) {
            access_token = refreshAccessToken(type);
        }
        return access_token;
    }
    
    public static String refreshAccessToken(Integer type) {
        String access_token;
        Integer expires_in;
        String appKey;
        String appSecret;
        String url;
        Map<String, Object> params = new HashMap<>();
        if(type == 1){
            appKey = ConfigValues.getItnAccessTokenKey();
            appSecret = ConfigValues.getItnAccessTokenSecret();
            url = ConfigValues.getItnAccessTokenUrl();
        }else{
            appKey = ConfigValues.getOpenApiAppKey();
            appSecret = ConfigValues.getOpenApiAppSecret();
            url = ConfigValues.getOpenApiAuthUrl();
            params.put("redirect_uri", ConfigValues.getOpenApiRedirectUri());
        }
        String authorization = "Basic " + Base64Helper.getBase64(appKey + ":" + appSecret);
        params.put("grant_type", "client_credentials");
        String result = HttpUtil.doPost(url, params, HttpUtil.CHARSET, authorization);
        if (StringUtils.isBlank(result)) {
            logger.error("获取openApi access_token失败：" + result);
            return null;
        }
        JSONObject json = JSONUtil.toJsonObject(result);
        access_token = json.getString("access_token");
        expires_in = json.getInteger("expires_in");
        if (StringUtils.isBlank(access_token)) {
            logger.error("获取openApi access_token失败：" + json.toJSONString());
            return null;
        }
        logger.debug("获取OpenApi Access_token成功：" + access_token);
        if(type == 1){
            SessionHelper.getInstance().setInfoForSession(CacheKeys.ITN_ACCESS_TOKEN, access_token,
                    getUpdateTimeout(expires_in));
        }else{
            SessionHelper.getInstance().setInfoForSession(CacheKeys.OPENAPI_ACCESS_TOKEN, access_token,
                    getUpdateTimeout(expires_in));
        }
        return access_token;
    }
    
    private static int getUpdateTimeout(Integer expires_in) {
        int expires_day = expires_in / 60 / 60 / 24;
        Calendar now = Calendar.getInstance();
        Calendar update = Calendar.getInstance();
        long time = 0l;
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH);
        int day = now.get(Calendar.DAY_OF_MONTH);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        if (hour < HOUR_TIMEOUT) {
            update.set(year, month, day + expires_day - 1, HOUR_TIMEOUT, 0, 0);
            time = (update.getTimeInMillis() - now.getTimeInMillis()) / 1000;
        } else {
            update.set(year, month, day + expires_day, HOUR_TIMEOUT, 0, 0);
            time = (update.getTimeInMillis() - now.getTimeInMillis()) / 1000;
        }
        return (int) time;
    }
}
